#include "Socket.h"
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

Socket::Socket()
{
}

Socket::~Socket()
{
}

void Socket::Init(int sock)
{
	SetHandler(sock);
}

int Socket::GetSockAddr(sockaddr_in& localaddr)
{
	socklen_t addrlen = sizeof(localaddr);
	if(getsockname(GetHandler(), reinterpret_cast<sockaddr*>(&localaddr), &addrlen) != -1)
		return 0;
	else
		return errno;
}

int Socket::GetPeerAddr(sockaddr_in& peeraddr)
{
	socklen_t addrlen = sizeof(peeraddr);
	if(getpeername(GetHandler(), reinterpret_cast<sockaddr*>(&peeraddr), &addrlen) != -1)
		return 0;
	else
		return errno;
}

int Socket::Send(const void* data, int* len)
{
	*len = send(GetHandler(), data, *len, 0);
	if(*len != -1)
		return 0;
	else
		return errno;
}

int Socket::Receive(void* data, int* len)
{
	*len = recv(GetHandler(), data, *len, 0);
	if(*len != -1)
		return 0;
	else
		return errno;
}

int Socket::ReceiveFully(void* data, int len)
{
	int remains = len;	// remains bytes count
	int recved = 0;		// received bytes count
	while(remains > 0)
	{
		int ret = Receive((char*)data + recved, &remains);
		if(ret != 0)
			return ret;
		if(remains < 1)
			return -1;
		recved += remains;
		remains = len - recved;
	}
	return 0;
}
